﻿using Ledict.ConditionExtract.DAL;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ledict.ConditionExtract.BLL.WorkProcess
{
    public class WorkThread_first_CrimeNew : WorkThread_first
    {
        public int MaxCount = 0;//处理总数
        private int _currentCount = 0;//处理当前数量

        protected TreeDataBLL trbll = new TreeDataBLL();
        protected Express_WordBLL wordbll = new Express_WordBLL();
        protected Express_AddElement addelementbll = new Express_AddElement();
        protected ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        protected Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        protected AboutRegexBLL aboutreg = new AboutRegexBLL();
        protected RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        protected ProcessDataSourceBLL datas = new ProcessDataSourceBLL();
        protected WorkThread_Public work = new WorkThread_Public();
        protected XmlLabel_LabelRelBLL xmlLabel_LabelRelBLL = new XmlLabel_LabelRelBLL();
        //private CaseCauseBLL casecausebll = new CaseCauseBLL();
        private StaticCacheBLL staticcache = new StaticCacheBLL();
        Express_MatchSituationBLL MatchSituationbll = new Express_MatchSituationBLL();
        //WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        NewIDBLL newid = new NewIDBLL();
        Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        CaseCauseDAL cause = new CaseCauseDAL();
        Express_SourceDAL expresssource = new Express_SourceDAL();
        DataTable causeDt = new DataTable();
        #region  准备开始
        /// <summary>
        /// 开始加工（一个案由）
        /// </summary>
        public override void execute_Start()
        {
            MaxCount = 0;
            _currentCount = 0;
            //2、待处理的数据(总数)-查询lucene索引
            MaxCount += CaseCauseCondDAL.GetExpressCount(conditon.SituationId);

            causeDt = cause.GetCriminalNodes(conditon.SituationId);

            DataRow[] items = causeDt.Select(" CC_ParentID='" + conditon.SituationId + "'", "CC_GlobalOrder asc");
            foreach(DataRow item in items)
            {
                if(expresssource.IsProcess(item["CC_ID"].ToString()))
                {
                    work.AddMatch_virtual("S" + item["CC_ID"].ToString(), "单一");
                    work.AddMatch_virtual("M" + item["CC_ID"].ToString(), "组合");

                    DataTable expressDt = CaseCauseCondDAL.GetExpress(item["CC_ID"].ToString());
                    DataTable dt = expressDt.Clone();
                    string crccode = "";
                    foreach (DataRow dr in expressDt.Rows)
                    {
                        DataRow[] arrdr = causeDt.Select("CC_ID='" + dr["CauseId"].ToString() + "'");
                        if(arrdr.Length>0)
                        {
                            dr["CC_GlobalOrder"] = arrdr[0]["CC_GlobalOrder"].ToString();
                            dr["AllParentId"] = arrdr[0]["AllParentId"].ToString() + ",";
                            string _crccode = dr["CC_TextCRCCode"].ToString();
                            if (crccode == _crccode)
                            {
                                dt.ImportRow(dr);
                            }
                            else
                            {
                                if (crccode != "")
                                {
                                    string ccIdList = OrganizeExpress(dt);
                                    DataRow temp_dr = dt.Rows[0];
                                    AddToExpress(temp_dr["CC_Formatting"].ToString(), temp_dr["CaseId"].ToString(), "150", item["CC_ID"].ToString(), ccIdList, dt.Rows.Count);
                                }
                                crccode = _crccode;
                                dt = new DataTable();
                                dt = expressDt.Clone();
                                dt.ImportRow(dr);
                            }
                        }                        

                        #region 处理完成后,进度条

                        _currentCount++; // 显示进度条
                        if (MaxCount >= _currentCount)
                        {
                            processShow(MaxCount, _currentCount);
                        }
                        #endregion 处理完成后,进度条
                    }
                }                
            }
           

        }

        private string OrganizeExpress(DataTable dt)
        {
            DataTable temp_dt = dt.Clone();
            string ccid = "";
            foreach(DataRow item in dt.Rows)
            {
                string _ccid = item["CauseId"].ToString();
                if(ccid == "" || ccid != _ccid)
                {
                    temp_dt.ImportRow(item);
                    ccid = _ccid;
                }
            }
            DataRow[] arrdr = temp_dt.Select("", "CC_GlobalOrder");
            DataRow dr = arrdr[0];
            string allcauseids = "";
            for (int i = 0; i < arrdr.Length; i++)
            {
                string causeId = arrdr[i]["CauseId"].ToString();
                //排除子节点和父节点的组合（按照业务，这个不算组合节点）
                if (temp_dt.Select("AllParentId like '%," + causeId + ",%'").Length == 1)
                {
                    allcauseids += arrdr[i]["CauseId"].ToString() + ",";
                }
            }
            return allcauseids.Substring(0, allcauseids.Length - 1);
        }
        #endregion

        #region 入库
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="CaseCauseID">案由小分类ID</param>
        /// <param name="ParagraphID">逻辑段140，150</param>
        /// <param name="resultText">索引句子</param>
        /// <param name="CC_IDList">ID字符串</param>
        /// <param name="caseid">案例ID</param>
        public void AddToExpress(string resultText, string caseid, string ParagraphID, string CaseCauseID, string CC_IDList,int userCount)
        {
            #region 添加match表

            //#region 节点属性
            bool ismatchb = System.Text.RegularExpressions.Regex.IsMatch(resultText, "(?<=^|。|\r|\n|；)[^。|；]*?(?:不构成|不符|不属).*?(?:。|；)");
            //getregex.IsMatch("3F53BB8A-08CC-4F55-89A9-8EAAE4FC3163", resultText);//true 不构成
            int ismatch = ismatchb ? 0 : 1;
            bool affirmIdeaResultb = System.Text.RegularExpressions.Regex.IsMatch(resultText, "(?<=^|。|\r|\n|；)[^。|；]*?(?:不[予能]?(认定|支持|认可|确认|采纳|采信)).*?(?:。|；)");
            //getregex.IsMatch("EI1601201151020001", resultText);//true 不认定
            string affirmIdeaResult = affirmIdeaResultb ? "2" : "1";

            string[] situationIDa = CC_IDList.Split(',');
            string situationIDs = "", msId = "", allParentId = "";
            List<SYS_Express_MatchSituation> situationList = new List<SYS_Express_MatchSituation>();
            for (int i = 0; i < situationIDa.Length; i++)
            {
                if (situationIDs == "") situationIDs = situationIDa[i];
                else situationIDs += "," + situationIDa[i];
                var stiuModel = new SYS_Express_MatchSituation();
                stiuModel.IsMatch = ismatch;
                stiuModel.AffirmIdeaResult = affirmIdeaResult;
                stiuModel.AllStituationIDs = situationIDs;
                stiuModel.MS_ID = MatchSituationbll.Exists_MatchSituation(stiuModel.IsMatch, stiuModel.AffirmIdeaResult, stiuModel.AllStituationIDs);//存在
                if(stiuModel.MS_ID == "")
                {
                    stiuModel.MS_ID = Guid.NewGuid().ToString();
                    stiuModel.SituationID = situationIDa[i];
                    DataRow[] arrdr = causeDt.Select("CC_ID='" + stiuModel.SituationID + "'");
                    stiuModel.SituationType = Convert.ToInt32(arrdr[0]["CC_NodeType"].ToString());
                    stiuModel.SituationName = string.Format("{0}（{1},{2}）", arrdr[0]["CC_Name"].ToString(), stiuModel.IsMatch == 1?"构成":"不构成", stiuModel.AffirmIdeaResult == "2"? ",不认定": ",认定");
                    if (i == 0) stiuModel.ParentID = CaseCauseID;
                    else stiuModel.ParentID = msId;                    
                    if (allParentId == "") allParentId = stiuModel.MS_ID;
                    else allParentId += "," + stiuModel.MS_ID;
                    stiuModel.AllParentID = allParentId;
                    stiuModel.CauseGroupID = CaseCauseID;
                    stiuModel.CC_IsShowExpress = 0;
                    situationList.Add(stiuModel);
                }
                else
                {
                    if (allParentId == "") allParentId = stiuModel.MS_ID;
                    else allParentId += "," + stiuModel.MS_ID;
                }
                msId = stiuModel.MS_ID;

            }
            if (situationList.Count > 0)
                MatchSituationbll.AddMatchSituation(situationList);
            #endregion

            #region 添加文本

            SYS_Express_Word wordModel = new SYS_Express_Word();
            wordModel.MS_ID = msId;


            wordModel.EW_CaseId = caseid;
            wordModel.EW_Content = resultText;

            wordModel.EW_UseCount = userCount;
            wordModel.EW_WordCount = resultText.Length;
            wordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);

            //wordModel.EW_ID = wordbll.Exists_WordProcess(wordModel);
            if (situationIDa.Length == 1) wordModel.EW_IsSingleExpress = 1;
            else wordModel.EW_IsSingleExpress = 0;


            //if (wordModel.EW_ID == "")
            //{
                wordModel.EW_ID = Guid.NewGuid().ToString();
                wordModel.EW_Right = 0;
                wordModel.EW_Wrong = 0;

                wordbll.AddWord_Process(wordModel);
            //}
            //else
            //{
            //wordbll.UpdateWord_Process(wordModel);
            //}
            #endregion

            #region 词库
            var ewAddElementStr = express_wordbankrelbll.WordBank("", wordModel.EW_Content);
            List<SYS_Express_WordBankRel> bankrelList = new List<SYS_Express_WordBankRel>();
            foreach (var item in ewAddElementStr)
            {
                SYS_Express_WordBankRel bankrel = new SYS_Express_WordBankRel()
                {
                    EWR_ID = Guid.NewGuid().ToString(),
                    EW_ID = wordModel.EW_ID,
                    WBK_ID = item
                };
                bankrelList.Add(bankrel);
            }
            if (bankrelList.Count > 0)
                express_wordbankrelbll.Add_Express_WordBankRel(bankrelList);
            #endregion
        }
        #endregion
    }
}
